import { BrowserRouter, Route, Routes } from 'react-router'
import { NotFound } from '@/pages/Exceptions'
import { BasicLayout } from '@/layout'
import Login from '@/pages/Login'
import Loading from '@/pages/Loading'
import { useUserInfo } from '@/store'
import RouteGuard from './RouteGuard'
import { MenuRouteVO } from '@/apis/payment.type'

const pageModules = import.meta.glob('/src/pages/**/**.tsx', { eager: true })

export default function BasicRouter() {
  const permissionMenuList = useUserInfo((state) => state.permissionList)

  const isMenuLoading = permissionMenuList.length === 0

  function loadRouteByMenu(menuList: MenuRouteVO[]) {
    return menuList.map((menu) => {
      const children = menu.routes
      if (children && children.length > 0) {
        return (
          <Route key={menu.path} path={menu.path}>
            {loadRouteByMenu(children)}
          </Route>
        )
      }
      const page = pageModules[`/src${menu.componentPath}/index.tsx`] as Record<string, any>
      const PageElement = page ? page.default : <NotFound />
      return <Route key={menu.path} path={menu.path} element={<PageElement />} />
    })
  }

  function renderAllRouteElement(
    height: string = '100vh',
    NotFoundHeight: string = 'calc(100vh - 56px)'
  ) {
    return isMenuLoading ? (
      <Loading styles={{ height }} />
    ) : (
      <NotFound style={{ height: NotFoundHeight }} />
    )
  }

  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/"
          element={
            <RouteGuard>
              <BasicLayout />
            </RouteGuard>
          }
        >
          {loadRouteByMenu(permissionMenuList)}
          <Route
            path="*"
            element={renderAllRouteElement('calc(100vh - 150px)', 'calc(100vh - 120px)')}
          />
        </Route>
        <Route path="login" element={<Login />} />
        <Route path="*" element={renderAllRouteElement()} />
      </Routes>
    </BrowserRouter>
  )
}
